<?php
//微信企业号
class BWeChatQyClass
{
    var $corpid = "";
    var $corpsecret = "";
     //构造函数，获取Access Token
    public function __construct($corpid = NULL, $corpsecret = NULL)
    {
        if($corpid){
            $this->corpid = $corpid;
        }
        if($corpsecret){
            $this->corpsecret = $corpsecret;
        }

        //hardcode
         $this->lasttime = 1395049256;
         $this->access_token = "nRZvVpDU7LxcSi7GnG2LrUcmKbAECzRf0NyDBwKlng4nMPf88d34pkzdNcvhqm4clidLGAS18cN1RTSK60p49zIZY4aO13sF-eqsCs0xjlbad-lKVskk8T7gALQ5dIrgXbQQ_TAesSasjJ210vIqTQ";

        if (time() > ($this->lasttime + 7200)){
            $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->corpid."&corpsecret=".$this->corpsecret;
            $res = $this->https_request($url);
            $result = json_decode($res, true);
            //save to Database or Memcache
            $this->access_token = $result["access_token"];
            $this->lasttime = time();
        }
    }
    //根据部门发送消息，文本类型
    public function sendMessageParty($topartyID, $type,$agent, $data)
    {
        $msg = array('toparty' =>$topartyID);
        switch($type)
        {
            case 'text':
                $msg['msgtype'] = 'text';
            	$msg['agentid'] = $agent;
                $msg['text']    = array('content'=> urlencode($data));
                break;
        }
        $url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=".$this->access_token;
        return $this->https_request($url, urldecode(json_encode($msg)));
    }
    //https请求（支持GET和POST）
    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
    
}
?>